import React, { useState, useEffect, useMemo } from 'react';
import { Button, Form, message, Modal, Space, Table, Empty } from 'antd';
import { SortableContainer, SortableHandle } from 'react-sortable-hoc';
import { getMessage, TextWidget } from '@inbiz/react';
import { uuid } from '@inbiz/utils';
import { MenuOutlined } from '@ant-design/icons';
import { EditableRow, EditableCell } from './OptionEditCell';

const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#666' }} />);
const SortableBody = SortableContainer((props: any) => <tbody {...props} />);

const EditableContext = React.createContext<any>(null);
export { EditableContext };
const processMessage = (res: string, key?: any) => {
  if (key) {
    return message.success({ content: res, key: 'inbizMessage' });
  }
  return message.error({ content: res, key: 'inbizMessage' });
};

const defaultOption = (props: any) => {
  const [visible, $visible] = useState(false);
  const [selectedRowKeys, $selectedRowKeys] = useState<any[]>([]);
  const [dataSource, $dataSource] = useState<any[]>(props.value || []);
  const [form] = Form.useForm();
  const [nowKey, $nowKey] = useState(null);

  const value_common = getMessage('ProcessManagement.value_common');
  const text_common = getMessage('ProcessManagement.text_common');

  useEffect(() => {
    $dataSource(props.value);
  }, [props.value]);

  const defaultColumns = [
    {
      title: getMessage('ProcessManagement.value'),
      dataIndex: 'key',
      width: '40%',
      editable: true,
      required: true,
    },
    {
      title: getMessage('ProcessManagement.text'),
      dataIndex: 'name',
      lang: true,
      width: '40%',
      editable: true,
      required: true,
    },
    {
      title: getMessage('ProcessManagement.sort'),
      dataIndex: 'sort',
      width: '10%',
      align: 'center',
      render: () => <DragHandle />,
    },
  ];

  //  添加
  const add = () => {
    $dataSource([
      ...dataSource,
      {
        id: uuid(20, 60),
        key: '',
        name: '',
      },
    ]);
  };

  // 删除
  const del = () => {
    if (selectedRowKeys?.length == 0) {
      processMessage(getMessage('ProcessManagement.selct_del_type'));
    }
    $dataSource(dataSource.filter((item: any) => !selectedRowKeys.includes(item.id)));
    $selectedRowKeys([]);
  };

  // 每次复选框发生变化时调用
  const onSelectChange = (newSelectedRowKeys: any) => {
    $selectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleSave = (row: any) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.id === item.id);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    $dataSource(newData);
  };

  const save = () => {
    let list: any[] = [...dataSource];
    let keys: string[] = [];
    let names: string[] = [];
    for (let i = 0; i < list?.length; i++) {
      for (let j = 0; j < defaultColumns?.length; j++) {
        if (defaultColumns[j].required) {
          let key = defaultColumns[j].dataIndex;
          if (!list[i][key] || list[i][key] === '') {
            let dom: any = document.getElementById(`cell-${key}-${list[i].id}`);
            dom.click();
            setTimeout(() => {
              form.validateFields();
            }, 0);
            return;
          }
        }
      }
      if (keys.includes(list[i].key)) {
        processMessage(value_common);
        return;
      }
      if (names.includes(list[i].name)) {
        processMessage(text_common);

        return;
      }
      keys.push(list[i].key);
      names.push(list[i].name);
    }
    props.onChange?.(list);
    $visible(false);
    $selectedRowKeys([]);
  };

  const onSortEnd = ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
    if (oldIndex !== newIndex) {
      let list = move(dataSource, oldIndex, newIndex);
      $dataSource(list);
    }
  };

  const Contoner = (props: any) => {
    return (
      <SortableBody
        useDragHandle
        lockAxis="y"
        helperClass="row-dragging"
        onSortEnd={onSortEnd}
        {...props}
      />
    );
  };

  const components = useMemo(
    () => ({
      body: {
        wrapper: Contoner,
        row: EditableRow(dataSource),
        cell: EditableCell,
      },
    }),
    [dataSource],
  );

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        editable: col.editable,
        required: col.required,
        dataIndex: col.dataIndex,
        title: col.title,
        lang: col.lang,
        nowKey: nowKey,
        setNowKey: (e: any) => $nowKey(e),
        handleSave,
      }),
    };
  });

  return (
    <>
      <Button
        type="primary"
        onClick={() => {
          $visible(true);
          $dataSource(props.value);
        }}
      >
        配置
      </Button>

      <Modal
        visible={visible}
        className="defalutOption-modal"
        title="流程类型"
        onCancel={() => {
          $visible(false);
          $selectedRowKeys([]);
        }}
        onOk={save}
        cancelText="取消"
        okText="确定"
      >
        <Space align="start" className="headerButton">
          <Button type="primary" onClick={add}>
            添加
          </Button>
          <Button
            onClick={() => {
              del();
            }}
            danger
            disabled={selectedRowKeys?.length == 0}
          >
            删除
          </Button>
        </Space>
        <Form form={form}>
          <EditableContext.Provider value={form}>
            <Table
              bordered
              // @ts-ignore
              columns={columns}
              dataSource={dataSource}
              rowSelection={rowSelection}
              components={components}
              rowKey="id"
              scroll={{ y: 190 }}
              rowClassName={'edit-able'}
              pagination={false}
              locale={{
                emptyText: (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description={<TextWidget>ProcessManagement.no_data</TextWidget>}
                  />
                ),
              }}
            ></Table>
          </EditableContext.Provider>
        </Form>
      </Modal>
    </>
  );
};
export default defaultOption;

/**
 * 拖拽后位置置换
 * @param array any[] 原数据数组
 * @param fromIndex number 原数据位置
 * @param toIndex number 新数据位置
 * @returns
 */
const move = (array: any[], fromIndex: number, toIndex: number) => {
  const newArray = [...array];
  const startIndex = fromIndex < 0 ? newArray?.length + fromIndex : fromIndex;
  if (startIndex >= 0 && startIndex < newArray?.length) {
    const endIndex = toIndex < 0 ? newArray?.length + toIndex : toIndex;
    const [item] = newArray.splice(fromIndex, 1);
    newArray.splice(endIndex, 0, item);
  }
  return newArray;
};
